.section .text.entry

.extern test
.global trap_s
.extern handler_s
.equ reg_size, 0x8
.align 2

trap_s:
	#save caller-saved registers and spec
	addi sp,sp,-136
	sd ra,(sp)
	sd t0,8(sp)
	sd t1,16(sp)
	sd t2,24(sp)
	sd a0,32(sp)
	sd a1,40(sp)
	sd a2,48(sp)
	sd a3,56(sp)
	sd a4,64(sp)
	sd a5,72(sp)
	sd a6,80(sp)
	sd a7,88(sp)
	sd t3,96(sp)
	csrr t3,sepc
	sd t3,104(sp)
	sd t4,112(sp)
	sd t5,120(sp)
	sd t6,128(sp)
	
	# call handler_s(scause)
	csrr a0,scause
	call handler_s

	# load sepc and callee-saved registers
	ld ra,(sp)
	ld t0,8(sp)
	ld t1,16(sp)
	ld t2,24(sp)
	ld a0,32(sp)
	ld a1,40(sp)
	ld a2,48(sp)
	ld a3,56(sp)
	ld a4,64(sp)
	ld a5,72(sp)
	ld a6,80(sp)
	ld a7,88(sp)
	ld t3,96(sp)
	ld t4,104(sp)
	csrw sepc,t4
	ld t4,112(sp)
	ld t5,120(sp)
	ld t6,128(sp)
	addi sp,sp,136
	sret


.globl __switch_to
__switch_to:
	li    a4,  40 
	add   a3, a0, a4
	add   a4, a1, a4
	#Save context into prev->thread
	/*your code*/
	sd ra,(a3)
	sd sp,8(a3)
	sd a0,16(a3)
	sd a1,24(a3)
	sd a2,32(a3)
	sd a3,48(a3)
	sd a4,56(a3)
	sd a5,64(a3)
	sd a6,72(a3)
	sd a7,80(a3)
	sd t0,88(a3)
	sd t1,64(a3)
	sd t2,72(a3)
	sd t3,80(a3)
	
	
	#Restore context from next->thread
	/*your code*/
	ld ra,(a4)
	ld sp,8(a4)
	ld a0,16(a4)
	ld a1,24(a4)
	ld a2,32(a4)
	ld a3,48(a4)
	ld a5,64(a4)
	ld a6,72(a4)
	ld a7,80(a4)
	ld t0,88(a4)
	ld t1,64(a4)
	ld t2,72(a4)
	ld t3,80(a4)
	ld a4,56(a4)
	
	#return to ra
	ret


.globl __init_sepc
__init_sepc:
	la  t0, test
	csrw sepc, t0
	sret
